package com.cxy.ch1.threadlocal;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* @ClassName: ThreadLocalOOM
* @Description: TODO(ThreadLocal造成的内存泄漏演示)
* @author 菜徐鸭
* @date 2020年4月13日
*
*/
public class ThreadLocalOOM {
	 private static final int TASK_LOOP_SIZE = 500;

	    final static ThreadPoolExecutor poolExecutor
	            = new ThreadPoolExecutor(5, 5,
	            1,
	            TimeUnit.MINUTES,
	            new LinkedBlockingQueue<>());

	    static class LocalVariable {
	        private byte[] a = new byte[1024*1024*5];/*5M大小的数组*/
	    }

	    final static ThreadLocal<LocalVariable> localVariable
	            = new ThreadLocal<>();

	    /**
	     * 想要避免内存泄漏，一定要在用户之后执行ThreadLocal.remove()方法
		 *	ThreadLocal.set()；会一定程度的回收
		 *  内存不够用叫内存溢出
		 *	回收不掉叫内存泄漏
	     * @param args
	     * @throws InterruptedException
	     */
	    public static void main(String[] args) throws InterruptedException {
	        Object o = new Object();
	        /*5*5=25*/
	        for (int i = 0; i < TASK_LOOP_SIZE; ++i) {
	            poolExecutor.execute(new Runnable() {
	                public void run() {
	                    //localVariable.set(new LocalVariable());
	                    new LocalVariable();
	                    System.out.println("use local varaible");
	                    //localVariable.remove();
	                }
	            });

	            Thread.sleep(100);
	        }
	        System.out.println("pool execute over");
	    }
}
